/*
 * Animation.cpp
 *
 *  Created on: 30/05/2013
 *      Author: vitor
 */

#include "Animation.h"

Animation::Animation(std::string fileName, int frameTimeInMilliseconds,
		int numRows, int* numberOfSpritesInEachRow, int spriteWidth,
		bool repeat) :
		Sprite(fileName) {

	_frameTimeInMilliseconds = frameTimeInMilliseconds;
	_numRows = numRows;
	_frameTimer.start(frameTimeInMilliseconds);
	_currentRow = 0;
	_currentFrame = 0;
	_ended = false;
	_repeat = repeat;

	for (int i = 0; i < _numRows; i++) {
		_numberOfSpritesInEachRow[i] = numberOfSpritesInEachRow[i];
	}

	_spriteWidth = spriteWidth;
	_spriteHeight = spriteSurface->h / _numRows;

	clipRect.w = spriteWidth;
	clipRect.h = spriteSurface->h / _numRows;

}

bool Animation::ended() const{
	return _ended;
}

Animation::~Animation() {
}

void Animation::update(double dt) {
	if (!_ended) {
		_frameTimer.update();
		if (_frameTimer.isDone()) {
			_frameTimer.start(_frameTimeInMilliseconds);
			if (_currentFrame >= _numberOfSpritesInEachRow[_currentRow]) {
				if (_repeat) {
					_currentFrame = 0;
				} else {
					_ended = true;
				}
			}
			clipRect.x = clipRect.w * _currentFrame;
			clipRect.y = clipRect.h * _currentRow;
			if (clipRect.x >= spriteSurface->w) {
				clipRect.x = (clipRect.x - spriteSurface->w) % spriteSurface->w;
			}
			clip(clipRect.x, clipRect.y, clipRect.w, clipRect.h);
			_currentFrame++;
		}
	}
}

void Animation::reset() {
	_ended = false;
	_currentFrame = 0;
}

void Animation::setFrame(int frame) {
	clipRect.x = clipRect.w * frame;
}

void Animation::setCurrentRow(int row) {
	_currentRow = row;
}

void Animation::render(int x, int y, bool center, SDL_Surface *destSurf) {
	if (!_ended) {
		Sprite::render(x, y, center, destSurf);
	}
}

